package com.wswy.wzcx.model.weather

import android.os.Parcel
import android.os.Parcelable
import java.util.*


class WeatherData() :Parcelable{
    var liveWeather: LiveWeather? = null

    var forecastResult: List<ForecastWeather>? = null
        set(value) {
            field = value
            if (value != null){
                calWashIndex(value)
            }
        }


    var washCarDesc:String?=null
    private set
    var washCarIndex = 4
    private set

    constructor(parcel: Parcel) : this() {
        liveWeather = parcel.readParcelable(LiveWeather::class.java.classLoader)
        parcel.readParcelableArray(ForecastWeather::class.java.classLoader)?.let {
            forecastResult = Arrays.copyOf(it,it.size,Array<ForecastWeather>::class.java).toList()
        }
    }


    private fun calWashIndex(list: List<ForecastWeather>){
        var washIndex = 0

        if (list.size <= 4){
            kotlin.run loop@{
                for (i in 0..3){
                    if (list[i].canWashCar()){
                        washIndex++
                    }else{
                        return@loop
                    }
                }
            }
        }

        if(washIndex > 0){
            washIndex --
        }

        washCarIndex = 4 - washIndex

        washCarDesc = when(washCarIndex){
            1 -> "适宜洗车"
            2 -> "较适宜洗车"
            3 -> "较不适宜洗车"
            4 -> "不适宜洗车"
            else -> null
        }

    }

    fun completed() = liveWeather != null && forecastResult != null

    fun reset() {
        washCarDesc = null
        washCarIndex = 4
        liveWeather = null
        forecastResult = null
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeParcelable(liveWeather, flags)
        parcel.writeParcelableArray(forecastResult?.toTypedArray(),flags)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<WeatherData> {
        override fun createFromParcel(parcel: Parcel): WeatherData {
            return WeatherData(parcel)
        }

        override fun newArray(size: Int): Array<WeatherData?> {
            return arrayOfNulls(size)
        }
    }
}